package pcp

import (
	"encoding/base64"
	"gitee.com/teval/uts"
	"github.com/forgoer/openssl"
)

// DesCBCEncrypt DesCBC加密
//
// 注意：key、iv都是固定长度：64bit，即8个字符（UTF-8）
func DesCBCEncrypt(value, key, iv string, pad ...string) (string, error) {
	var p = openssl.PKCS5_PADDING
	if len(pad) > 0 {
		p = uts.Nvl(pad[0], p)
	}
	a := NewDesCBCCrypt(key, iv, p)
	return a.Encrypt([]byte(value))
}

func DesCBCDecrypt(value, key, iv string, pad ...string) (string, error) {
	var p = openssl.PKCS5_PADDING
	if len(pad) > 0 {
		p = uts.Nvl(pad[0], p)
	}
	a := NewDesCBCCrypt(key, iv, p)
	return a.Decrypt(value)
}

func NewDesCBCCrypt(key, iv string, pad ...string) (desCBCCrypt *DesCBCCrypt) {
	desCBCCrypt = &DesCBCCrypt{
		Key:     []byte(key),
		Iv:      []byte(iv),
		Padding: openssl.PKCS5_PADDING,
	}

	if len(pad) > 0 {
		desCBCCrypt.Padding = pad[0]
	}

	return
}

type DesCBCCrypt struct {
	Key     []byte
	Iv      []byte
	Padding string
}

func (a *DesCBCCrypt) Encrypt(src []byte) (rst string, err error) {
	dst, err := openssl.DesCBCEncrypt(src, a.Key, a.Iv, a.Padding)
	if err != nil {
		return
	}
	rst = base64.StdEncoding.EncodeToString(dst)
	return
}

func (a *DesCBCCrypt) Decrypt(data string) (rst string, err error) {
	src, err := base64.StdEncoding.DecodeString(data)
	if err != nil {
		return
	}
	dst, err := openssl.DesCBCDecrypt(src, a.Key, a.Iv, a.Padding)
	if err != nil {
		return
	}
	rst = string(dst)
	return
}
